package com.xqls.biz.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xqls.bean.UserRoleKeyBean;
import com.xqls.biz.UserRoleKeyBiz;
import com.xqls.dal.model.User;
import com.xqls.dal.model.UserRoleKey;
import com.xqls.service.UserRoleKeyService;
import com.xqls.service.UserService;
import com.xqls.util.CommonPage;
import com.xqls.util.CommonResult;
import com.xqls.util.ObjectUtil;
import com.xqls.util.VelocityUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserRoleKeyBizImpl implements UserRoleKeyBiz {

	private static Logger logger = Logger.getLogger(UserRoleKeyBiz.class);

	@Autowired
	private UserService userService;

	@Autowired
	private UserRoleKeyService userRoleKeyService;

	@Override
	public CommonResult insertUserRole(Map<String, Object> map) {
		CommonResult commonResult = new CommonResult();

		User user = new User();
		user.setUserId((String) map.get("userId"));
		user.setUserName((String) map.get("userName"));
		user.setPassword((String) map.get("password"));
		user.setName((String) map.get("name"));
		user.setTelephone((String) map.get("telephone"));
		user.setMsgAlertLevel(Integer.valueOf((String) map.get("msgAlertLevel")));
		user.setBlockId(Integer.valueOf((String) map.get("blockId")));

		UserRoleKey userRoleKey = new UserRoleKey();
		userRoleKey.setRoleId((String) map.get("roleId"));
		userRoleKey.setUserId((String) map.get("userId"));
		
		try {
			if (this.userService.getUserByUserName((String) map.get("userName")).size() > 0) {
				commonResult.setResultMsg("账户名重复!");
			} else {
				String userId=null;
				if(this.userService.insertUser(user))
				{
					userId=this.userService.getLastRecord((String) map.get("userName")).getUserId();
					userRoleKey.setUserId(userId);
					if(this.userRoleKeyService.insertDate(userRoleKey))
					{
						commonResult.setIsSuccess(true);
					}
					else
					{
						commonResult.setResultMsg("插入用户关联角色信息失败");
					}
				}
				else
				{
					commonResult.setResultMsg("插入用户信息失败");
				}
			}
		} catch (Exception e) {
			logger.error("用户配置添加异常", e);
		}
		return commonResult;
	}

	@Override
	public CommonResult updateUserRole(Map<String, Object> map) {
		CommonResult commonResult = new CommonResult();

		User user = new User();
		user.setUserId((String) map.get("userId"));
		user.setUserName((String) map.get("userName"));
		user.setPassword((String) map.get("password"));
		user.setName((String) map.get("name"));
		user.setTelephone((String) map.get("telephone"));
		user.setMsgAlertLevel(Integer.valueOf((String) map.get("msgAlertLevel")));
		user.setBlockId(Integer.valueOf((String) map.get("blockId")));

		UserRoleKey userRoleKey = new UserRoleKey();
		userRoleKey.setRoleId((String) map.get("roleId"));
		userRoleKey.setUserId((String) map.get("userId"));

		List<User> userList = null;
		boolean isUpdateUser=false;
		boolean isUpdateUserRole=false;
		try {
			userList = this.userService.getUserByUserName((String) map.get("userName"));
			for (User userGet : userList) {
				if (!userGet.getUserId().equals(user.getUserId())) {
					commonResult.setResultMsg("用户名重复");
					return commonResult;
			    }
			}
	        
	        isUpdateUser=this.userService.updateUser(user);
	        isUpdateUserRole=this.userRoleKeyService.updateData(userRoleKey, (String) map.get("oldRoleId"));
			commonResult.setIsSuccess(isUpdateUser && isUpdateUserRole);
		} catch (Exception e) {
			logger.error("用户配置修改异常", e);
		}
		return commonResult;
	}

	@Override
	public CommonResult deleteUserRole(UserRoleKeyBean userRoleKeyBean) {
		CommonResult commonResult = new CommonResult();
		UserRoleKey userRoleKey = null;
		boolean isDeletedUserRole = false;
		boolean isDeletedUser = false;
		try {
			userRoleKey = (UserRoleKey) ObjectUtil.transfer(userRoleKeyBean, UserRoleKey.class);
			isDeletedUserRole = this.userRoleKeyService.deleteData(userRoleKey);
			isDeletedUser = this.userService.deleteUser(userRoleKeyBean.getUserId());
			commonResult.setIsSuccess(isDeletedUserRole && isDeletedUser);
		} catch (Exception e) {
			logger.error("用户配置删除异常", e);
		}
		return commonResult;
	}

	@Override
	public CommonResult getListByPage(CommonPage commonPage, HttpServletRequest request, HttpServletResponse response) {
		CommonResult commonResult = new CommonResult();
		try {
			commonPage.setPageData(this.userRoleKeyService.getListByMap(commonPage.pageToMap()));
			Map<String, Object> showMap = new HashMap<String, Object>();
			showMap.put("userRoleList", commonPage.getPageData());
			commonPage.setHtml(VelocityUtil.getHtmlByMap("userRole/userRoleListData.vm", showMap,request,response,request.getSession().getServletContext()));
			commonResult.setIsSuccess(true);
		} catch (Exception e) {
			logger.error("用户配置查询异常", e);
		}
		return commonResult;
	}

	@Override
	public Map<String, Object> getUserRoleBeanById(String userId) {
		List<Map<String, Object>> userRoleList = null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);

		try {
			userRoleList = this.userRoleKeyService.getListByMap(map);
			if (!userRoleList.isEmpty()) {
				map = userRoleList.get(0);
			}
		} catch (Exception e) {
			logger.error("用户配置查询异常", e);
		}
		return map;
	}

	@Override
	public CommonResult deleteByList(List<UserRoleKeyBean> keyBeanList) {
		CommonResult commonResult = new CommonResult();
		List<String> userIdList = new ArrayList<String>();
		List<String> roleIdList = new ArrayList<String>();
		
		boolean isDeletedUserRole = false;
		boolean isDeletedUser = false;
		try {
			for (UserRoleKeyBean userRoleKeyBean : keyBeanList) {
				userIdList.add(userRoleKeyBean.getUserId());
				roleIdList.add(userRoleKeyBean.getRoleId());
			}
			isDeletedUserRole = this.userRoleKeyService.deleteByList(userIdList, roleIdList);
			isDeletedUser = this.userService.deleteByList(userIdList);
			commonResult.setIsSuccess(isDeletedUserRole && isDeletedUser);
		} catch (Exception e) {
			logger.error("用户配置删除异常",e);
		}

		return commonResult;
	}

}
